<?php

namespace app\admin\controller\building;

use app\admin\model\BuildingRoomBoardModel;
use app\admin\model\BuildingRoomFixedModel;
use app\admin\model\BuildingZoneModel;
use app\admin\model\House;
use app\common\controller\Backend;
use app\admin\model\ConfigValueModel;
use app\admin\model\UserConfigChargeModel;
use app\admin\model\BuildingModel;
use app\admin\model\BuildingRoomModel;
use app\admin\model\BuildingRoomPtModel;
use think\Db;
use think\Loader;

/**
 * 楼栋房间管理
 *
 * @icon fa fa-circle-o
 */
class Room extends Backend
{

    /**
     * Room模型对象
     * @var \app\admin\model\building\Room
     */
    protected $model = null;
    protected $dataLimitField = 'user_id';
    protected $dataLimit = true;
    protected $dataLimitFieldAutoFill = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\building\Room;
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("houseStatusList", [2 => '未上架', 1 => '已上架',3 => '已出租']);

//        $chargeList = UserConfigChargeModel::where('user_id',$this->auth->id)
//            ->field(['id', 'name', 'money', 'pay_type'])
//            ->select();
//        foreach ($chargeList  as $item) {
//            $item->append(['pay_type_text']);
//        }
//
//        $this->view->assign("chargeList", $chargeList);
//
//
//        $building_ids = BuildingModel::getUserBuildingIds($this->auth->id);
//        $room_ids = BuildingRoomModel::whereIn('build_id', $building_ids)->column('id');
//        $ptList = BuildingRoomPtModel::group('name')
//            ->whereIn('room_id', $room_ids)
//            ->field('name,num,deposit,remark')
//            ->select();
//
//        $this->view->assign("ptList", $ptList);
    }

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->with(['zone', 'buildingName', 'house'])
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    protected function buildparams($searchfields = null, $relationSearch = null)
    {
        $searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
        $relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
        $search = $this->request->get("search", '');
        $filter = $this->request->get("filter", '');
        $op = $this->request->get("op", '', 'trim');
        $sort = $this->request->get("sort", !empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
        $order = $this->request->get("order", "DESC");
        $offset = $this->request->get("offset/d", 0);
        $limit = $this->request->get("limit/d", 999999);
        //新增自动计算页码
        $page = $limit ? intval($offset / $limit) + 1 : 1;
        if ($this->request->has("page")) {
            $page = $this->request->get("page/d", 1);
        }
        $this->request->get([config('paginate.var_page') => $page]);
        $filter = (array)json_decode($filter, true);
        $op = (array)json_decode($op, true);
        $filter = $filter ? $filter : [];
        $where = [];
        $alias = [];
        $bind = [];
        $name = '';
        $aliasName = '';
        if (!empty($this->model) && $this->relationSearch) {
            $name = $this->model->getTable();
            $alias[$name] = Loader::parseName(basename(str_replace('\\', '/', get_class($this->model))));
            $aliasName = $alias[$name] . '.';
        }
        $sortArr = explode(',', $sort);
        foreach ($sortArr as $index => & $item) {
            $item = stripos($item, ".") === false ? $aliasName . trim($item) : $item;
        }
        unset($item);
        $sort = implode(',', $sortArr);
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $where[] = [$aliasName . $this->dataLimitField, 'in', $adminIds];
        }
        if ($search) {
            $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
            foreach ($searcharr as $k => &$v) {
                $v = stripos($v, ".") === false ? $aliasName . $v : $v;
            }
            unset($v);
            $where[] = [implode("|", $searcharr), "LIKE", "%{$search}%"];
        }
        $index = 0;
        if (!empty($filter['zone_name'])) {
            $filter['zone_id'] = $filter['zone_name'];
            unset($filter['zone_name']);
        }
        if (!empty($filter['build_name'])) {
            $filter['build_id'] = $filter['build_name'];
            unset($filter['build_name']);
        }
        foreach ($filter as $k => $v) {
            if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', $k)) {
                continue;
            }
            $sym = isset($op[$k]) ? $op[$k] : '=';
            if (stripos($k, ".") === false) {
                $k = $aliasName . $k;
            }
            $v = !is_array($v) ? trim($v) : $v;
            $sym = strtoupper(isset($op[$k]) ? $op[$k] : $sym);
            //null和空字符串特殊处理
            if (!is_array($v)) {
                if (in_array(strtoupper($v), ['NULL', 'NOT NULL'])) {
                    $sym = strtoupper($v);
                }
                if (in_array($v, ['""', "''"])) {
                    $v = '';
                    $sym = '=';
                }
            }

            switch ($sym) {
                case '=':
                case '<>':
                    $where[] = [$k, $sym, (string)$v];
                    break;
                case 'LIKE':
                case 'NOT LIKE':
                case 'LIKE %...%':
                case 'NOT LIKE %...%':
                    $where[] = [$k, trim(str_replace('%...%', '', $sym)), "%{$v}%"];
                    break;
                case '>':
                case '>=':
                case '<':
                case '<=':
                    $where[] = [$k, $sym, intval($v)];
                    break;
                case 'FINDIN':
                case 'FINDINSET':
                case 'FIND_IN_SET':
                    $v = is_array($v) ? $v : explode(',', str_replace(' ', ',', $v));
                    $findArr = array_values($v);
                    foreach ($findArr as $idx => $item) {
                        $bindName = "item_" . $index . "_" . $idx;
                        $bind[$bindName] = $item;
                        $where[] = "FIND_IN_SET(:{$bindName}, `" . str_replace('.', '`.`', $k) . "`)";
                    }
                    break;
                case 'IN':
                case 'IN(...)':
                case 'NOT IN':
                case 'NOT IN(...)':
                    $where[] = [$k, str_replace('(...)', '', $sym), is_array($v) ? $v : explode(',', $v)];
                    break;
                case 'BETWEEN':
                case 'NOT BETWEEN':
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr, function ($v) {
                            return $v != '' && $v !== false && $v !== null;
                        })) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'BETWEEN' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'BETWEEN' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, $sym, $arr];
                    break;
                case 'RANGE':
                case 'NOT RANGE':
                    $v = str_replace(' - ', ',', $v);
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr)) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'RANGE' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'RANGE' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $tableArr = explode('.', $k);
                    if (count($tableArr) > 1 && $tableArr[0] != $name && !in_array($tableArr[0], $alias) && !empty($this->model)) {
                        //修复关联模型下时间无法搜索的BUG
                        $relation = Loader::parseName($tableArr[0], 1, false);
                        $alias[$this->model->$relation()->getTable()] = $tableArr[0];
                    }
                    $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' TIME', $arr];
                    break;
                case 'NULL':
                case 'IS NULL':
                case 'NOT NULL':
                case 'IS NOT NULL':
                    $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
                    break;
                default:
                    break;
            }
            $index++;
        }
        if (!empty($this->model)) {
            $this->model->alias($alias);
        }
        $model = $this->model;
        $where = function ($query) use ($where, $alias, $bind, &$model) {
            if (!empty($model)) {
                $model->alias($alias);
                $model->bind($bind);
            }
            foreach ($where as $k => $v) {
                if ($v[0] == 'house.status') {
                    if ($v[2] == 3) {
                        $query->where('status', 3);
                    } else {
                        $query->whereExists(
                            function ($query) use ($v) {
                                $query->name('house')
                                    ->where('fa_house.room_id = fa_building_room.id')
                                    ->where('fa_house.status', $v[2]);
                            }
                        );
                    }
                    continue;
                }
                if (is_array($v)) {
                    call_user_func_array([$query, 'where'], $v);
                } else {
                    $query->where($v);
                }
            }
        };
        return [$where, $sort, $order, $offset, $limit, $page, $alias, $bind];
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
     
     /**
     * 保存房源信息
     */
    public function add()
    {
        // 获取请求数据
        if (false === $this->request->isPost()) {
            $this->assign_option();
            return $this->view->fetch();
        }
        $data = $this->request->post('row/a');
        if (empty($data)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $data['tags'] = implode(',', $data['tags'] ?? []);
        $data['community'] = 1;
        $data['images'] = $data['images'] ? json_encode(explode(',', $data['images'])) : '';
        // 启动事务
        Db::startTrans();
        try {
            if ($data['type'] == 1) {
                $data['house_type'] = sprintf('%d室%d厅%d卫', $data['room_num'] ?? 0, $data['ting_num'] ?? 0, $data['toilet_num'] ?? 0);
            }
            $this->saveHouseType($data);
            // 1. 保存房源基本信息到building_room表
            $roomData = [
                'user_id' => $this->auth->id,
                'build_id' => $data['build_id'] ?? 0,
                'zone_id' => $data['zone_id'] ?? 0,
                'name' => $data['name'] ?? '',
                'type' => $data['type'] ?? 0,
                'house_type' => $data['house_type'] ?? '',
                'floor_no' => $data['floor_no'] ?? 0,
                'status' => $data['status'] ?? 0,
                'price' => $data['rent'] ?? 0.00,
                'original_price' => $data['original_price'] ?? 0.00,
                'area' => $data['area'] ?? '',
                'images' => $data['images'] ?? '',
                'remark' => $data['remark'] ?? '',
                'is_remind' => $data['is_remind'] ?? 0,
                'remind_day' => $data['remind_day'] ?? 0,
                'room_num' => $data['type'] == 1 ? ($data['room_num'] ?? 0) : 0,
                'ting_num' => $data['type'] == 1 ? ($data['ting_num'] ?? 0) : 0,
                'toilet_num' => $data['type'] == 1 ? ($data['toilet_num'] ?? 0) : 0,
                'create_time' => time(),
                'update_time' => time()
            ];
            
            $roomId = Db::name('building_room')->insertGetId($roomData);
            
            if (!$roomId) {
                throw new \Exception('保存房源基本信息失败');
            }
            
//            // 2. 处理yibiaojson数据并保存到building_room_board表
//            if (!empty($data['yibiaojson'])) {
//                $yibiaoData = json_decode($data['yibiaojson'],true);
//
//                if (is_array($yibiaoData)) {
//                    foreach ($yibiaoData as $item) {
//                        $yibiaoInsert = [
//                            'room_id' => $roomId,
//                            'type' => $item['type'] ?? '',
//                            'name' => $item['name'] ?? '',
//                            'price' => $item['price'] ?? 0,
//                            'min_num' => $item['min_num'] ?? 0,
//                            'last_num' => $item['last_num'] ?? 0,
//                            'sn' => $item['sn'] ?? '',
//                            'remark' => $item['remark'] ?? '',
//                            'create_time' => time(),
//                            'update_time' => time()
//                        ];
//
//                        $result = Db::name('building_room_board')->insert($yibiaoInsert);
//                        if (!$result) {
//                            throw new \Exception('保存仪表信息失败');
//                        }
//                    }
//                }
//            }
//
//            // 3. 处理fixedjson数据并保存到building_room_fixed表
//            if (!empty($data['fixedjson'])) {
//                $fixedData = json_decode($data['fixedjson'],true);
//
//                if (is_array($fixedData)) {
//                    foreach ($fixedData as $item) {
//                        $fixedInsert = [
//                            'room_id' => $roomId,
//                            'type_name' => $item['type_name'] ?? '',
//                            'price' => $item['price'] ?? 0,
//                            'pay_type' => $item['pay_type'] ?? 0,
//                            'first_use' => $item['first_use'] ?? 0,
//                            'create_time' => time(),
//                            'update_time' => time()
//                        ];
//
//                        $result = Db::name('building_room_fixed')->insert($fixedInsert);
//                        if (!$result) {
//                            throw new \Exception('保存固定费用信息失败');
//                        }
//                    }
//                }
//            }
//
//            // 4. 处理ptjson数据并保存到building_room_pt表
//            $facilities = [];
//            if (!empty($data['ptjson'])) {
//                $ptData = json_decode($data['ptjson'],true);
//
//                if (is_array($ptData)) {
//                    foreach ($ptData as $item) {
//                        $ptInsert = [
//                            'room_id' => $roomId,
//                            'name' => $item['name'] ?? '',
//                            'num' => $item['num'] ?? 0,
//                            'deposit' => $item['deposit'] ?? 0,
//                            'remark' => $item['remark'] ?? '',
//                            'option_id' => $item['id'],
//                            'create_time' => time(),
//                            'update_time' => time()
//                        ];
//                        $facilities[] = $item['id'];
//                        $result = Db::name('building_room_pt')->insert($ptInsert);
//                        if (!$result) {
//                            throw new \Exception('保存配套设备信息失败');
//                        }
//                    }
//                }
//            }

            if (!empty($data['fixed'])) {
                $fixed_data = [];
                $board_data = [];
                foreach ($data['fixed'] as $item) {
                    if (empty($item['checked']) || empty($item['price'])) {
                        continue;
                    }
                    $fixed_data[] = [
                        'room_id' => $roomId,
                        'cfg_id' => $item['id'],
                        'type_name' => $item['name'],
                        'price' => $item['price'],
                    ];

                    if (in_array($item['id'], [1, 2, 3])) {
                        $board_data[] = [
                            'room_id' => $roomId,
                            'type' => $item['id'],
                            'name' => $item['name'],
                            'price' => $item['price'],
                        ];
                    }

                }
                if ($fixed_data) {
                    (new BuildingRoomFixedModel())->allowField(true)->saveAll($fixed_data);
                }
                if ($board_data) {
                    (new BuildingRoomBoardModel())->allowField(true)->saveAll($board_data);
                }
            }

            // 配套处理
            $facilities = [];
            if (!empty($data['pt'])) {
                $pt_data = [];
                foreach ($data['pt'] as $item) {
                    if (empty($item['checked'])) {
                        continue;
                    }
                    $pt_data[] = [
                        'room_id' => $roomId,
                        'option_id' => $item['id'],
                        'name' => $item['name'],
                    ];
                    $facilities[] = $item['id'];

                }
                if ($pt_data) {
                    (new BuildingRoomPtModel())->allowField(true)->saveAll($pt_data);
                }
            }
            // 同步添加房源
            $house = new House();
            $data['room_id'] = $roomId;
            $data['user_id'] = $this->auth->id;
            $data['name'] = $data['title'];
            $data['floor'] = $data['floor_no'];
            $data['status'] = 1;
            $data['facilities'] = implode(',', $facilities);
            $data['region'] = BuildingZoneModel::where('id', $data['zone_id'])->value('name', '');
            $house->allowField(true)->save($data);
            // 更新水电费用
            BuildingRoomModel::syncHouseData($roomId, $house);

            // 提交事务
            Db::commit();
            return json(['code'=>1,'msg'=>'保存成功']);
            
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['code'=>0,'msg'=>'保存失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 编辑房屋信息
     */
    public function edit($ids = NULL)
    {
        // 获取请求数据
        $roomId = $ids;
        $row = $this->model->get($ids, ['house', 'fixed', 'pt']);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            // "type,name,price,sn,min_num,last_num,remark"
            //$row['yibiaojson'] = json_encode(Db::name('building_room_board')->where('room_id', $roomId)->field("type,name,price,sn,min_num,last_num,remark")->select(),JSON_UNESCAPED_UNICODE);
            // "type_name,price,pay_type,first_use"
            //$row['fixedjson'] = json_encode(Db::name('building_room_fixed')->where('room_id', $roomId)->field("type_name,price,pay_type,first_use")->select(),JSON_UNESCAPED_UNICODE);
            // "name,num,deposit,remark"
            //$row['ptjson'] = json_encode(Db::name('building_room_pt')->where('room_id', $roomId)->field("name,num,deposit,remark")->select(),JSON_UNESCAPED_UNICODE);

            $row = $row->toArray();
            if ($row['type'] == 1) {
                $row['room_num'] = 1;
                $row['ting_num'] = 0;
                $row['toilet_num'] = 0;
                if (preg_match('/^(\d+)室(\d+)厅(\d+)卫$/', $row['house']['house_type'] ?? '', $matches)) {
                    $row['room_num'] = $matches[1];
                    $row['ting_num'] = $matches[2];
                    $row['toilet_num'] = $matches[3];
                }
            }
            $row['house']['tags'] = array_filter(explode(',', $row['house']['tags']));
            $row['pt'] = array_column($row['pt'], 'option_id');
            $row['fixed'] = array_column($row['fixed'], null, 'cfg_id');
            if ($row['images']) {
                $row['images'] = implode(',', json_decode($row['images'], true));
            }
            $this->view->assign('row', $row);
            $this->assign_option();
            return $this->view->fetch();
        }
    
        $data = $this->request->post('row/a');
        $data['tags'] = implode(',', $data['tags'] ?? []);
        $data['community'] = 1;
        $data['images'] = $data['images'] ? json_encode(explode(',', $data['images'])) : '';
        // 启动事务
        Db::startTrans();
        try {
            if ($data['type'] == 1 && empty($data['house_type'])) {
                $data['house_type'] = sprintf('%d室%d厅%d卫', $data['room_num'] ?? 0, $data['ting_num'] ?? 0, $data['toilet_num'] ?? 0);
            }
            $this->saveHouseType($data);
            // 1. 更新房源基本信息到building_room表
            $roomData = [
                'build_id' => $data['build_id'] ?? 0,
                'zone_id' => $data['zone_id'] ?? 0,
                'name' => $data['name'] ?? '',
                'type' => $data['type'] ?? 0,
                'house_type' => $data['house_type'] ?? '',
                'floor_no' => $data['floor_no'] ?? 0,
                'status' => $data['status'] ?? 0,
                'price' => $data['price'] ?? 0.00,
                'original_price' => $data['original_price'] ?? 0.00,
                'area' => $data['area'] ?? '',
                'images' => $data['images'] ?? '',
                'remark' => $data['remark'] ?? '',
                'is_remind' => $data['is_remind'] ?? 0,
                'remind_day' => $data['remind_day'] ?? 0,
                'room_num' => $data['type'] == 1 ? ($data['room_num'] ?? 0) : 0,
                'ting_num' => $data['type'] == 1 ? ($data['ting_num'] ?? 0) : 0,
                'toilet_num' => $data['type'] == 1 ? ($data['toilet_num'] ?? 0) : 0,
                'update_time' => time()
            ];
            
            $result = Db::name('building_room')->where('id', $roomId)->update($roomData);
            
            if ($result === false) {
                throw new \Exception('更新房源基本信息失败');
            }
            
//            // 2. 删除原有的yibiaojson数据
//            Db::name('building_room_board')->where('room_id', $roomId)->delete();
//
//            // 重新插入yibiaojson数据
//            if (!empty($data['yibiaojson'])) {
//                $yibiaoData = json_decode($data['yibiaojson'],true);
//
//                if (is_array($yibiaoData)) {
//                    foreach ($yibiaoData as $item) {
//                        $yibiaoInsert = [
//                            'room_id' => $roomId,
//                            'type' => $item['type'] ?? '',
//                            'name' => $item['name'] ?? '',
//                            'price' => $item['price'] ?? 0,
//                            'min_num' => $item['min_num'] ?? 0,
//                            'last_num' => $item['last_num'] ?? 0,
//                            'sn' => $item['sn'] ?? '',
//                            'remark' => $item['remark'] ?? '',
//                            'create_time' => time(),
//                            'update_time' => time()
//                        ];
//
//                        $result = Db::name('building_room_board')->insert($yibiaoInsert);
//                        if (!$result) {
//                            throw new \Exception('更新仪表信息失败');
//                        }
//                    }
//                }
//            }
//
//            // 3. 删除原有的fixedjson数据
//            Db::name('building_room_fixed')->where('room_id', $roomId)->delete();
//
//            // 重新插入fixedjson数据
//            if (!empty($data['fixedjson'])) {
//                $fixedData = json_decode($data['fixedjson'],true);
//
//                if (is_array($fixedData)) {
//                    foreach ($fixedData as $item) {
//                        $fixedInsert = [
//                            'room_id' => $roomId,
//                            'type_name' => $item['type_name'] ?? '',
//                            'price' => $item['price'] ?? 0,
//                            'pay_type' => $item['pay_type'] ?? 0,
//                            'first_use' => $item['first_use'] ?? 0,
//                            'create_time' => time(),
//                            'update_time' => time()
//                        ];
//
//                        $result = Db::name('building_room_fixed')->insert($fixedInsert);
//                        if (!$result) {
//                            throw new \Exception('更新固定费用信息失败');
//                        }
//                    }
//                }
//            }
//
//            // 4. 删除原有的ptjson数据
//            Db::name('building_room_pt')->where('room_id', $roomId)->delete();
//
//            // 重新插入ptjson数据
//            $facilities = [];
//            if (!empty($data['ptjson'])) {
//                $ptData = json_decode($data['ptjson'],true);
//
//                if (is_array($ptData)) {
//                    foreach ($ptData as $item) {
//                        $ptInsert = [
//                            'room_id' => $roomId,
//                            'name' => $item['name'] ?? '',
//                            'num' => $item['num'] ?? 0,
//                            'deposit' => $item['deposit'] ?? 0,
//                            'remark' => $item['remark'] ?? '',
//                            'option_id' => $item['id'],
//                            'create_time' => time(),
//                            'update_time' => time()
//                        ];
//                        $facilities[] = $item['id'];
//                        $result = Db::name('building_room_pt')->insert($ptInsert);
//                        if (!$result) {
//                            throw new \Exception('更新配套设备信息失败');
//                        }
//                    }
//                }
//            }
            BuildingRoomBoardModel::destroy(['room_id' => $roomId], true);
            BuildingRoomFixedModel::destroy(['room_id' => $roomId], true);
            BuildingRoomPtModel::destroy(['room_id' => $roomId], true);
            if (!empty($data['fixed'])) {
                $fixed_data = [];
                $board_data = [];
                foreach ($data['fixed'] as $item) {
                    if (empty($item['checked']) || empty($item['price'])) {
                        continue;
                    }
                    $fixed_data[] = [
                        'room_id' => $roomId,
                        'cfg_id' => $item['id'],
                        'type_name' => $item['name'],
                        'price' => $item['price'],
                    ];

                    if (in_array($item['id'], [1, 2, 3])) {
                        $board_data[] = [
                            'room_id' => $roomId,
                            'type' => $item['id'],
                            'name' => $item['name'],
                            'price' => $item['price'],
                        ];
                    }

                }
                if ($fixed_data) {
                    (new BuildingRoomFixedModel())->allowField(true)->saveAll($fixed_data);
                }
                if ($board_data) {
                    (new BuildingRoomBoardModel())->allowField(true)->saveAll($board_data);
                }
            }

            // 配套处理
            $facilities = [];
            if (!empty($data['pt'])) {
                $pt_data = [];
                foreach ($data['pt'] as $item) {
                    if (empty($item['checked'])) {
                        continue;
                    }
                    $pt_data[] = [
                        'room_id' => $roomId,
                        'option_id' => $item['id'],
                        'name' => $item['name'],
                    ];
                    $facilities[] = $item['id'];
                }
                if ($pt_data) {
                    (new BuildingRoomPtModel())->allowField(true)->saveAll($pt_data);
                }
            }
            // 同步添加房源
            $house = House::where('room_id', $roomId)->order('id', 'desc')->find();
            if (empty($house)) {
                $house = new House();
            }
            $data['room_id'] = $roomId;
            $data['user_id'] = $this->auth->id;
            $data['name'] = $data['title'];
            $data['floor'] = $data['floor_no'];
            $data['status'] = 1;
            $data['facilities'] = implode(',', $facilities);
            $data['region'] = BuildingZoneModel::where('id', $data['zone_id'])->value('name', '');
            $house->allowField(true)->save($data);
            // 更新水电费用
            BuildingRoomModel::syncHouseData($roomId, $house);

            // 提交事务
            Db::commit();
            return json(['code'=>1,'msg'=>'更新成功']);
            
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['code'=>0,'msg'=>'更新失败: ' . $e->getMessage()]);
            
        }
    }

    public function saveHouseType(&$params)
    {
        if ($params['house_save_type'] == 'input') {
            Db::name('user_config_hx')->insert(
                [
                    'user_id' => $this->auth->id,
                    'name'    => $params['house_type_name'],
                ]
            );
            $params['house_type'] = $params['house_type_name'];
        }
        if (empty($params['house_type'])) {
            $this->error('户型信息必填');
        }
    }

    /**
     * 复制房屋信息
     */
    public function copy($ids)
    {
        // 启动事务
        Db::startTrans();
        $roomId = $ids;
        try {
            // 1. 获取原房源基本信息
            $originalHouse = Db::name('building_room')->where('id', $roomId)->find();
            
            if (!$originalHouse) {
                throw new \Exception('原房源信息不存在');
            }
            
            // 移除原ID和时间字段
            unset($originalHouse['id']);
            unset($originalHouse['create_time']);
            unset($originalHouse['update_time']);
            unset($originalHouse['delete_time']);
            unset($originalHouse['del_uid']);
            
            // 修改房源名称，添加复制标识
            $originalHouse['name'] = $originalHouse['name'] . '_复制';
            $originalHouse['create_time'] = time();
            $originalHouse['update_time'] = time();
            
            // 插入新的房屋信息
            $newRoomId = Db::name('building_room')->insertGetId($originalHouse);
            
            if (!$newRoomId) {
                throw new \Exception('复制房源基本信息失败');
            }
            
            // 2. 复制仪表信息
            $yibiaoList = Db::name('building_room_board')
                ->where('room_id', $roomId)
                ->select();
            
            if (!empty($yibiaoList)) {
                foreach ($yibiaoList as $yibiao) {
                    unset($yibiao['id']);
                    unset($yibiao['delete_time']);
                    $yibiao['room_id'] = $newRoomId;
                    $yibiao['create_time'] = time();
                    $yibiao['update_time'] = time();
                    
                    $result = Db::name('building_room_board')->insert($yibiao);
                    if (!$result) {
                        throw new \Exception('复制仪表信息失败');
                    }
                }
            }
            
            // 3. 复制固定费用信息
            $fixedList = Db::name('building_room_fixed')
                ->where('room_id', $roomId)
                ->select();
            
            if (!empty($fixedList)) {
                foreach ($fixedList as $fixed) {
                    unset($fixed['id']);
                    unset($fixed['delete_time']);
                    $fixed['room_id'] = $newRoomId;
                    $fixed['create_time'] = time();
                    $fixed['update_time'] = time();
                    
                    $result = Db::name('building_room_fixed')->insert($fixed);
                    if (!$result) {
                        throw new \Exception('复制固定费用信息失败');
                    }
                }
            }
            
            // 4. 复制配套设备信息
            $ptList = Db::name('building_room_pt')
                ->where('room_id', $roomId)
                ->select();
            
            if (!empty($ptList)) {
                foreach ($ptList as $pt) {
                    unset($pt['id']);
                    unset($pt['delete_time']);
                    $pt['room_id'] = $newRoomId;
                    $pt['create_time'] = time();
                    $pt['update_time'] = time();
                    
                    $result = Db::name('building_room_pt')->insert($pt);
                    if (!$result) {
                        throw new \Exception('复制配套设备信息失败');
                    }
                }
            }
            
            // 提交事务
            Db::commit();
            return json(['code'=>1,'msg'=>'复制成功']);
            
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['code'=>0,'msg'=>'复制失败: ' . $e->getMessage()]);
        }
    }

    public function assign_option()
    {
        $community = (new ConfigValueModel())->getOptionListWithIcon(2);
        $pt        = (new ConfigValueModel())->getOptionListWithIcon(4);
        $tag       = (new ConfigValueModel())->getOptionListWithIcon(8);
        $cost      = Db::name('cost_config')->field('id,name,icon,unit')->select();
        $hx        = Db::name('user_config_hx')
            ->where('user_id', $this->auth->id)
            ->field(['id', 'name', 'room_num', 'kt_num', 'toilet_num', 'sort_num', 'type'])
            ->order(['sort_num' => 'asc', 'id' => 'desc'])
            ->select();

        $this->view->assign('houseTypeList', $hx);
        $this->view->assign('paymentTypeList', ['押一付一', '押一付二', '押一付三', '押二付一', '押二付二', '押二付三', '押三付一', '押零付一']);
        $this->view->assign('communityList', $community);
        $this->view->assign('peitaoList', $pt);
        $this->view->assign('tagList', $tag);
        $this->view->assign('costList', $cost);
    }
}
